package com.jushu.storbox.database;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.entities.UploadObject;
import com.jushu.storbox.util.LogUtil;
import com.huawei.sharedrive.sdk.android.util.StringUtil;

public class UploadFileDao  extends BaseDao  implements IUploadFileDao {
	
	private final static String TABLE_NAME_UPLOAD_NOTIFY_LIST = "tb_upload_notify_list";
	private final static String LOG_TAG = "UploadFileDao";
	
	@Override
	public long getLastUpdateTime(String objectId) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	@Override
	public void updateLastUpdateTime(String objectId) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public long insertFile(UploadObject fileInfo) {
		LogUtil.i(LOG_TAG , "fileInfo.getName():"+fileInfo.getName());
		long row = -1;
		try {
			UploadObject fileInfoResponse = getUploadFileFileInfoById(fileInfo.getLoctPath(), fileInfo.getOwnerId());
			Log.e(LOG_TAG, "fileInfo.getLoctPath():"+fileInfo.getLoctPath());
			if(null != fileInfoResponse){
				LogUtil.e(LOG_TAG , "fileDao no need insertFile, id identical");
				return row;
			}
			ContentValues cv = fileInfo.toContentValues();
			row = this.getDb().insert(TABLE_NAME_UPLOAD_FILE_LIST, null, cv);
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "insertFile fail:" + e.getLocalizedMessage());
		}
		return row;
	}
	
	public int updateUploadObject(UploadObject fileInfo) {
		String whereClause = IBaseDao.owner_by + " = ? and "
				+IBaseDao.parent_folder_id + " = ? and "
				+IBaseDao.local_path + " =? ";
		String[] whereArgs = new String[]{ fileInfo.getOwnerBy(), fileInfo.getParent(), fileInfo.getLoctPath()};
		
		return this.getDb().update(TABLE_NAME_UPLOAD_FILE_LIST, 
				fileInfo.toContentValues(), 
				whereClause, 
				whereArgs);
	}

	@Deprecated
	@Override
	public void deleteFile(String fileId, String ownerId) {
		try {
			if (!StringUtil.isBlank(fileId)) {
				this.getDb().execSQL("delete from " + TABLE_NAME_UPLOAD_FILE_LIST + " where "
						+IBaseDao.id+" = ? and "+IBaseDao.owner_by+" =? ",
						new String[] { fileId, ownerId });
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "deleteFile is fail:" + e.getLocalizedMessage());
		}
	}
	
	public void deleteFile(UploadObject fileInfo) {
		try {
				this.getDb().execSQL("delete from " + TABLE_NAME_UPLOAD_FILE_LIST + " where "
						+IBaseDao.local_path+" = ? and "
						+IBaseDao.parent_folder_id+" = ? and "
						+IBaseDao.owner_by+" =? ",
						new String[] { fileInfo.getLoctPath(), fileInfo.getParent(), fileInfo.getOwnerBy()});
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "deleteFile is fail:" + e.getLocalizedMessage());
		}
	}
	
	@Override
	public long insertNotify(int notifyId) {
		long row = -1;
		try {
			ContentValues cv = new ContentValues();
			cv.put(DBHelper.NOTIFY_ID, notifyId);
			cv.put(DBHelper.NOTIFY_CREATE_TIME, (new Date()).getTime());
			row = this.getDb().insert(TABLE_NAME_UPLOAD_NOTIFY_LIST, null, cv);
		} catch (Exception e) {
			
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "insertNotify fail:" + e.getLocalizedMessage());
		}
		return row;
	}

	@Override
	public void deleteNotify(int notifyId) {
		try {
			this.getDb().execSQL("delete from " + TABLE_NAME_UPLOAD_NOTIFY_LIST + " where "
					+ DBHelper.NOTIFY_ID + " = ? ",
					new Integer[] { notifyId });
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "deleteNotify is fail:" + e.getLocalizedMessage());
		}
	}
	
	@Override
	public void deleteAllNotify() {
		try {
			this.getDb().execSQL("delete from " + TABLE_NAME_UPLOAD_NOTIFY_LIST,new String[]{});
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "deleteAllNotify is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void updateUploadState(String fileId, String ownerId, int transStatus) {
		try {
			if(!StringUtil.isBlank(fileId)){
				String whereCase = IBaseDao.id +" = ? and "+IBaseDao.owner_by+"=? ";
				String whereArgs[] = new String[] {fileId, ownerId};
				ContentValues cv = new ContentValues();
				cv.put(IBaseDao.trans_status, transStatus);
				this.getDb().update(TABLE_NAME_UPLOAD_FILE_LIST, cv, whereCase, whereArgs);
			}	
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "ShareDriveApplication.getInstance().getWnerID():" + e.getLocalizedMessage());
		}
	}

	@Override
	public List<UploadObject> getUploadFileList() {
		String sql = "select * from " + TABLE_NAME_UPLOAD_FILE_LIST +" where "+current_user_id+" =?";
		String[] sqlArgument = new String[] {ShareDriveApplication.getInstance().getWnerID()};
		return queryForResult(sql, sqlArgument);
	}
	
	@Override
	public List<UploadObject> getComplateUploadFileList() {
		String sql = "select * from " + TABLE_NAME_UPLOAD_FILE_LIST 
				+" where "+current_user_id+" =? and "+IBaseDao.trans_status+"=?";
		String[] sqlArgument = new String[] {ShareDriveApplication.getInstance().getWnerID(), ""+Constant.TRANSLATE_IS_SUCCESS};
		return queryForResult(sql, sqlArgument);
	}
	
	public List<UploadObject> getNotComplateUploadFileList() {
		String sql = "select * from " + TABLE_NAME_UPLOAD_FILE_LIST 
				+" where "+current_user_id+" =? and "+IBaseDao.trans_status+"<>?";
		String[] sqlArgument = new String[] {ShareDriveApplication.getInstance().getWnerID(), ""+Constant.TRANSLATE_IS_SUCCESS};
		return queryForResult(sql, sqlArgument);
	}
	
	public List<UploadObject> getAlbumBackupFailuredLi() {
		String sql = "select * from " + TABLE_NAME_UPLOAD_FILE_LIST 
				+" where "+current_user_id+" =? and "+IBaseDao.trans_status+"=? and "+IBaseDao.type+"=?";
		String[] sqlArgument = new String[] {ShareDriveApplication.getInstance().getWnerID(), ""+Constant.TRANSLATE_IS_FAILURED, ""+Constant.UPLOAD_TYPE_ALBUM};
		return queryForResult(sql, sqlArgument);
	}
	
	private List<UploadObject> queryForResult(String sql, String[] selectionArgs) {
		List<UploadObject> fileInfoList = new ArrayList<UploadObject>();
		Cursor cursor = null;
		try {
			cursor = this.getDb().rawQuery(sql, selectionArgs);
			while(cursor.moveToNext()) {
				UploadObject uploadObj = new UploadObject();
				uploadObj.fromCursor(cursor);
				fileInfoList.add(uploadObj);
			}
		} catch (Exception e) {
			LogUtil.e(LOG_TAG, "getFileList fail:" + e.getLocalizedMessage());
		} finally {
			if(cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
		cursor = null;
		LogUtil.d("UploadObject--->fileInfoList:"+fileInfoList.size());
		return fileInfoList;
	}
	
	@Override
	public List<Integer> getNotifyList() {
		List<Integer> notifyList = new ArrayList<Integer>();
		try {
			Cursor cursor = this.getDb().rawQuery(
					"select * from " + TABLE_NAME_UPLOAD_NOTIFY_LIST,new String[]{});
			if (!cursor.moveToFirst()) {
				return notifyList;
			}
			do {
				notifyList.add(cursor.getInt(cursor.getColumnIndex(DBHelper.NOTIFY_ID)));
			} while (cursor.moveToNext());
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "getNotifyList fail:" + e.getLocalizedMessage());
		}
		return notifyList;
	}

	@Override
	public UploadObject getUploadFileFileInfoById(String fileId, String ownerId) {
		UploadObject fileInfo = null;
		try {
			Cursor cursor = this.getDb().rawQuery(
					"select * from " + TABLE_NAME_UPLOAD_FILE_LIST + " where "
							+ IBaseDao.id +" = ? and "+IBaseDao.owner_by+"=?",
					new String[] {fileId, ownerId});
			if (!cursor.moveToFirst()) {
				return fileInfo;
			}
			fileInfo = new UploadObject();
			do {
				fileInfo.fromCursor(cursor);
			} while (cursor.moveToNext());
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "getFileList fail:" + e.getLocalizedMessage());
			return null;
		}
		return fileInfo;
	}

	@Override
	public UploadObject getUploadFileFileInfoBySha1(String Sha1, String folderId, String ownerId) {
		UploadObject fileInfo = null;
		try {
			Cursor cursor = this.getDb().rawQuery(
					"select * from " + TABLE_NAME_UPLOAD_FILE_LIST + " where "
							+ IBaseDao.file_sha1 +"=? and "+IBaseDao.parent_folder_id+" = ? and "+IBaseDao.owner_by+"=?",
					new String[] {Sha1,folderId, ownerId});
			if (!cursor.moveToFirst()) {
				return fileInfo;
			}
			fileInfo = new UploadObject();
			do {
				fileInfo.fromCursor(cursor);
			} while (cursor.moveToNext());
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "getFileList fail:" + e.getLocalizedMessage());
			return null;
		}
		return fileInfo;
	}
	
	@Override
	public UploadObject getUploadFile(String ownerId, String folderId, String filePath) {
		UploadObject fileInfo = null;
		try {
			Cursor cursor = this.getDb().rawQuery(
					"select * from " + TABLE_NAME_UPLOAD_FILE_LIST + " where "
							+ IBaseDao.local_path +"=? and "+IBaseDao.parent_folder_id+" = ? and "+IBaseDao.owner_by+"=?",
					new String[] {filePath, folderId, ownerId});
			if (cursor != null) {
				if(cursor.moveToFirst()) {
					fileInfo = new UploadObject();
					fileInfo.fromCursor(cursor);
				}
				cursor.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "getFileList fail:" + e.getLocalizedMessage());
			return null;
		}
		return fileInfo;
	}

	@Override
	public void updateUploadUrl(String fileId, String ownerId, String uploadUrl) {
		try {
			if(!StringUtil.isBlank(fileId)){
				this.getDb().execSQL("update " + TABLE_NAME_UPLOAD_FILE_LIST 
						+ " set " + IBaseDao.upload_path + " = ? where "
						+ IBaseDao.id +" = ? and "+IBaseDao.owner_by+"=?",
						new String[] { uploadUrl, fileId, ownerId});
			}	
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "update transStatus is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void updateCurrentIndex(String fileId, String ownerId, String indexFinished) {
		try {
			if(!StringUtil.isBlank(fileId)){
				this.getDb().execSQL("update " + TABLE_NAME_UPLOAD_FILE_LIST 
						+ " set " + IBaseDao.current_index + " = ? where "
						+ IBaseDao.id +" = ? and "+IBaseDao.owner_by+"=?",
						new String[] { indexFinished, fileId, ownerId});
			}	
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "update transStatus is fail:" + e.getLocalizedMessage());
		}
	}
	
	@Override
	public void updateProgress(String fileId, String ownerId, long currentProgress) {
		try {
			if(!StringUtil.isBlank(fileId)){
				
				String whereCase = IBaseDao.id +" = ? and "+IBaseDao.owner_by+"=?";
				String whereArgs[] = new String[] {
						fileId, ownerId
					};
				ContentValues cv = new ContentValues();
				cv.put(IBaseDao.trans_status, Constant.TRANSLATE_IS_RUNNING);
				cv.put(IBaseDao.current_progress, currentProgress);
				this.getDb().update(TABLE_NAME_UPLOAD_FILE_LIST, cv, whereCase, whereArgs);
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "update transStatus is fail:" + e.getLocalizedMessage());
		} 
	}
}
